package com.jinunn.system.secutity.service;

import com.jinunn.system.model.dto.UserAuthInfoDto;
import com.jinunn.system.secutity.model.SysUserDetail;
import com.jinunn.system.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author Jindun
 * @version SysUserDetailsService.java, v0.1 2024年 07⽉ 11⽇  上午9:31 Jindun Exp $
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SysUserDetailsService implements UserDetailsService {

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            UserAuthInfoDto userAuthInfoDto = userService.getUserAuthInfo(username);
            if (Objects.isNull(userAuthInfoDto)) {
                throw new UsernameNotFoundException(username);
            }
            return new SysUserDetail(userAuthInfoDto);
        } catch (Exception e) {
            // 记录异常日志
            log.error("认证异常:{}", e.getMessage());
            // 抛出异常
            throw e;
        }
    }
}
